module.exports = ( app ) => {

	// Add headers
	app.use ( (req, res, next) =>  {

	    res.setHeader ( 'Access-Control-Allow-Origin', '*' );

	    res.setHeader ( 'Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE' );

	    res.setHeader ( 'Access-Control-Allow-Headers', 'X-Requested-With,content-type' );

  		res.setHeader ( 'Access-Control-Allow-Credentials', true );

	    next (  );
	} );

	app.get ( app.config.api + '/cost/:id', ( req, res, next ) => {

		( new app.config.models.Cost (  ) ).search ( { "id": req.params.id }, ( resp ) => {

      res.send ( resp )
    } )
	} )

  app.delete ( app.config.api + '/cost/:id', ( req, res, next ) => {

  	( new app.config.models.Cost (  ) ).removeCost ( {
			"id": req.params.id
		}, ( resp ) => {

      res.send ( resp )
    } )
  } )

	app.get ( app.config.api + '/cost', ( req, res, next ) => {

		( new app.config.models.Cost (  ) ).show ( ( resp ) => {

      res.send ( resp )
    } )
	} )

	app.put ( app.config.api + '/cost/:id', ( req, res, next ) => {

		( new app.config.models.Cost (  ) ).update( {
        type: req.body.type,
        value: req.body.value,
      }, {
        email: req.body.emailBefore
      }, ( resp ) => {

        res.send ( resp )
      } )

	} )

	app.post ( app.config.api + '/cost', ( req, res, next ) => {

		let dataRequest = {
      type: req.body.type,
      value: req.body.value,
    }

		let cost = ( new app.config.models.Cost (  ) )

		let valueCheckFields = cost.check({valid: {
		      value: true,
		      data: dataRequest
		    }
		})

		if ( valueCheckFields.status ) {

   		cost.add( dataRequest, ( resp ) => {

        res.send ( resp )
      } )
		} else {

		  res.send ( {
				status: "error"
			} )
		}

	} )

	return app
}
